import { api, tokenName, timeout, codeName, code, contentType } from "@/config";
import store from "@/store/index";

// 封装请求方法
const request = async (url = "", method = "GET", data = {}, header = {}) => {
  //请求拦截
  const result = await interceptor_request({
    request: {
      baseUrl: api(),
      url: url,
      method: method,
      data: data,
      header: header,
    },
  });

  return new Promise((resolve, reject) => {
    uni.request({
      url: result.baseUrl + result.url,
      method: result.method,
      data: result.data,
      header: result.header,
      timeout,
      success: async (res) => {
        //响应拦截
        const response = await interceptor_response({
          response: res,
        });
        resolve(response);
      },
      fail: (err) => {
        uni.showToast({
          title: "" + err.errMsg,
          icon: "none",
        });
        // reject(err);
      },
    });
  });
};

/*
 * @date: 2023-12-20 11:39:02
 * description: 请求拦截器
 * @param {*}
 * @return {*} {}
 */

const interceptor_request = (chain) => {
  return new Promise((resolve) => {
    let token = uni.getStorageSync("token");
    let dataType = chain.request.header["content-type"];
    chain.request.header[tokenName] = token ? token : "X-Token";
    chain.request.header["content-type"] = dataType ? dataType : contentType;
    resolve(chain.request);
  });
};

/*
 * @date: 2023-12-20 13:10:10
 * description: 响应拦截器
 * @param {*}
 * @return {*} {}
 */
const interceptor_response = (chain) => {
  return new Promise((resolve) => {
    let stateCode = chain.response.data[codeName];
    if (stateCode) {
      switch (stateCode) {
        case code:
          resolve(chain.response.data);
          break;
        case 401:
          interceptor_401();
          break;
        case true: //免费接口返回的code码为true
          resolve(chain.response.data);
      }
    } else {
      uni.showToast({
        title: "无法获取后端接口返回的code码",
        icon: "none",
      });
    }
  });
};
//401
const interceptor_401 = () => {
  uni.showToast({
    title: "登录失效，请重新登录",
    icon: "none",
  });
  // 调用vuex的退出登录方法
  store.dispatch("user/logout");
};
// uniapp请求拦截
// uni.addInterceptor('request', {
//   // 请求拦截器
//   invoke: (args) => {
//     console.log('请求拦截器', args)
//   }
// })
// // uniapp响应拦截
// uni.addInterceptor('response', {
//   // 响应拦截器
//   invoke: (args) => {
//     console.log('响应拦截器', args)
//   }
// })

export default request;
